package edu.hm.swe2.shareit.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Persistence;
import javax.persistence.TypedQuery;

import edu.hm.swe2.shareit.domain.Exemplar;
import edu.hm.swe2.shareit.domain.Resource;

public class ExemplarDAO {

	private static EntityManager emgr = 
		Persistence.createEntityManagerFactory("ShareItJPA").createEntityManager();

	public void create(Exemplar entity) {
		emgr.getTransaction().begin();
		emgr.persist(entity);
		emgr.getTransaction().commit();
	}

	public Exemplar read(int id) {
		return emgr.find(Exemplar.class, id);
	}

	public void update(Exemplar entity) {
		emgr.getTransaction().begin();
		emgr.merge(entity);
		emgr.getTransaction().commit();
	}

	public void delete(Exemplar entity) {
		emgr.getTransaction().begin();
		entity = emgr.merge(entity);
		emgr.remove(entity);
		emgr.getTransaction().commit();
	}

	public List<Exemplar> findByResource(Resource res) {
		TypedQuery<Exemplar> tq = emgr.createQuery(
				"select object(e) from Exemplar e where e.resource.id = ?1",
				Exemplar.class);
		tq.setParameter(1, res.getId());
		return tq.getResultList();
	
	}

}
